<template>
  <div class="product-management">
    <!-- 查询区域 -->
    <el-card shadow="never" class="query-card">
      <el-form :model="queryParams" :inline="true" label-width="70px" ref="queryFormRef">
        <!-- 产品名称 -->
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable style="width: 200px" />
        </el-form-item>

        <!-- 所属机构 -->
        <el-form-item label="所属机构" prop="belongInstitutionName">
          <el-input v-model="queryParams.belongInstitutionName" placeholder="请输入机构名称" clearable style="width: 200px" />
        </el-form-item>

        <!-- 审核状态 -->
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择" clearable style="width: 140px">
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核驳回" value="2" />
          </el-select>
        </el-form-item>

        <!-- 主担保类型 -->
        <el-form-item label="主担保类型" label-width="auto" prop="mainGuaranteeWay">
          <el-select v-model="queryParams.mainGuaranteeWay" placeholder="请选择" clearable style="width: 190px">
            <el-option v-for="(item, index) in productMainGuaranteeType" :key="index" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 申请时间 -->
        <el-form-item label="申请时间" prop="applyTimeRange">
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="queryParams.applyTimeRange"
            type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 300px" />
        </el-form-item>

        <!-- 审核时间 -->
        <el-form-item label="审核时间" prop="auditTimeRange">
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="queryParams.auditTimeRange"
            type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 300px" />
        </el-form-item>

        <!-- 查询与重置 -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-card">
      <div>
        <el-button type="primary" style="margin-bottom: 16px;" @click="handleAdd">新增产品</el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%" header-cell-class-name="table-header"
        @selection-change="handleSelectionChange">
        <!-- 多选 -->
        <el-table-column type="selection" width="40" align="center" />

        <!-- 产品编号 -->
        <el-table-column prop="productSerialNumber" label="产品编号" width="200" show-overflow-tooltip align="center" />

        <!-- LOGO -->
        <el-table-column label="Logo" width="80" align="center">
          <template #default="{ row }">
            <el-image :src="row.productLogo" fit="cover" style="width: 40px; height: 40px; border-radius: 4px;" />
          </template>
        </el-table-column>

        <!-- 产品名称 -->
        <el-table-column prop="productName" label="产品名称" width="100" align="center" />

        <!-- 所属机构 -->
        <el-table-column prop="belongInstitutionName" label="所属机构" width="100" align="center" />

        <!-- 主担保方式 -->
        <el-table-column prop="mainGuaranteeWay" label="主担保方式" width="120"
          :formatter="(row) => transformDict('productMainGuaranteeType', row.mainGuaranteeWay)" align="center" />

        <!-- 二级担保方式 -->
        <el-table-column prop="secondGuaranteeWay" label="二级担保方式" width="110" align="center"
          :formatter="(row) => transformDict('productSecondGuaranteeWay', row.secondGuaranteeWay)" />

        <!-- 额度范围(万) -->
        <el-table-column prop="amountRange" label="额度范围(万)" width="120" align="center">
          <template #default="{ row }">
            {{ row.amountLimitLower }} - {{ row.amountLimitUpper }} 万
          </template>
        </el-table-column>

        <!-- 贷款期限(月) -->
        <el-table-column prop="loanTerm" label="贷款期限(月)" width="110" align="center">
          <template #default="{ row }">
            {{ row.loanPeriodLimitLower }} - {{ row.loanPeriodLimitUpper }} 月
          </template>
        </el-table-column>

        <!-- 参考年利率(%) -->
        <el-table-column prop="interestRate" label="参考年利率(%)" width="130" align="center">
          <template #default="{ row }">
            {{ row.interestRateLimitLower }} - {{ row.interestRateLimitUpper }} %
          </template>
        </el-table-column>

        <!-- 还款方式 -->
        <el-table-column prop="repaymentWay" label="还款方式"
          :formatter="row => transformDict('repaymentType', row.repaymentWay)" width="100" align="center" />

        <!-- 排序 -->
        <!-- <el-table-column prop="sortOrder" label="排序" width="50" align="center" /> -->

        <!-- 利率显示 -->
        <el-table-column prop="interestRateShow" label="利率显示" width="100" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.interestRateShow" @change="handleSwitchInterestRateShow(row)" active-value="1"
              inactive-value="0" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column prop="enabled" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.enabled" @change="handleSwitchEnabled(row)" active-value="1" inactive-value="0"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
          </template>
        </el-table-column>

        <!-- 审核状态 -->
        <el-table-column prop="auditStatus" label="审核状态" width="100" align="center"
          :formatter="row => transformDict('auditStatus', row.auditStatus)">
        </el-table-column>

        <!-- 申请时间 -->
        <el-table-column prop="createTime" label="申请时间" width="100" align="center" />

        <!-- 申请人 -->
        <el-table-column prop="createBy" label="申请人" width="80" align="center" />

        <!-- 申请人来源 -->
        <el-table-column prop="publishSource" label="申请人来源"
          :formatter="row => transformDict('productApplySource', row.publishSource)" width="130" align="center" />

        <!-- 审核人 -->
        <el-table-column prop="auditor" label="审核人" width="80" align="center" />

        <!-- 审核时间 -->
        <el-table-column prop="auditTime" label="审核时间" width="100" align="center" />

        <!-- 操作 -->
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="success" @click="handleView(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination" style="margin-top: 20px; text-align: right">

        <el-pagination class="mt-5" v-model:current-page="queryParams.pageNum" :total="total" background
          @current-change="getList" layout="prev, pager, next" />
      </div>
    </el-card>

    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="产品基本信息" name="basicInfo">
          <el-form ref="basicInfoRef" :disabled="formDisabled" :model="form" :rules="rules" label-width="110px">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="产品类型" prop="productType">
                  <el-select v-model="form.productType" placeholder="请选择产品类型" clearable>
                    <el-option v-for="dict in productType" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="form.productName" placeholder="请输入产品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品简称" prop="productShortName">
                  <el-input v-model="form.productShortName" placeholder="请输入产品简称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属金融机构" prop="belongInstitution">
                  <!-- <el-autocomplete v-model="form.belongInstitutionName" class="w-full" value-key="orgName"
                    @select="handleSelectOrg" :fetch-suggestions="querySearch" clearable placeholder="请输入机构名称" /> -->
                  <el-select v-model="form.belongInstitution" placeholder="请选择所属金融机构" @change="handleSelectOrg"
                    clearable>
                    <el-option v-for="item in organizationList" :key="item.orgPath" :label="item.orgName"
                      :value="item.orgPath" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="主担保方式" prop="mainGuaranteeWay">
                  <el-select v-model="form.mainGuaranteeWay" placeholder="请选择主担保方式" clearable>
                    <el-option v-for="dict in productMainGuaranteeType" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="二级担保方式" prop="secondGuaranteeWay">
                  <el-select v-model="form.secondGuaranteeWay" placeholder="请选择二级担保方式" clearable>
                    <el-option v-for="dict in productSecondGuaranteeWay" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审批模式" prop="auditMode">
                  <el-select v-model="form.auditMode" placeholder="请选择审批模式" clearable>
                    <el-option v-for="dict in productApproveMode" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="线上地址类型" prop="onlineAddressType">
                  <el-radio-group v-model="form.onlineAddressType">
                    <el-radio v-for="(item, index) in productOnlineAddressType" :value="item.label">{{
                      item.label
                    }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="线上地址" prop="onlineAddressUrl">
                  <el-input v-if="form.onlineAddressType === '链接地址'" v-model="form.onlineAddressUrl"
                    placeholder="请输入线上地址" />
                  <div v-else class="flex gap-3">
                    <!-- <el-upload class="upload-demo" :show-file-list="false"
                      :action="`${VITE_APP_BASE_URL}/common/upload`"
                      :headers="{ 'Authorization': 'Bearer ' + getToken() }" :limit="1"
                      :on-success="(res) => form.onlineAddressUrl = res.url">
                      <el-button type="primary">点击上传</el-button>
                    </el-upload> -->
                    <OneUpload isBtn v-model="form.onlineAddressUrl"></OneUpload>
                    <el-button type="primary" @click="showImg = true">查看图片</el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="额度范围(万)" prop="amountLimitLower">
                  <el-input v-model="form.amountLimitLower" placeholder="最低额度" style="width: 45%" />
                  <span style="display: inline-block; width: 10%; text-align: center">~</span>
                  <el-input v-model="form.amountLimitUpper" placeholder="最高额度" style="width: 45%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="利率范围(%)" prop="interestRateLimitLower">
                  <el-input v-model="form.interestRateLimitLower" placeholder="最低利率" style="width: 45%" />
                  <span style="display: inline-block; width: 10%; text-align: center">~</span>
                  <el-input v-model="form.interestRateLimitUpper" placeholder="最高利率" style="width: 45%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="显示利率" prop="interestRateShow">
                  <el-switch v-model="form.interestRateShow" active-value="1" inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="贷款期限(月)" prop="loanPeriodLimitLower">
                  <el-input v-model="form.loanPeriodLimitLower" placeholder="最短期限" style="width: 45%" />
                  <span style="display: inline-block; width: 10%; text-align: center">-</span>
                  <el-input v-model="form.loanPeriodLimitUpper" placeholder="最长期限" style="width: 45%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="还款方式" prop="repaymentWay">
                  <el-select v-model="form.repaymentWay" placeholder="请选择还款方式" clearable>
                    <el-option v-for="dict in repaymentType" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="排序" prop="sort">
                  <el-input-number v-model="form.sort" placeholder="请输入排序值" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="适用区域" prop="scope">
                  <el-radio-group v-model="form.scope" @change="handleScopeChange">
                    <el-radio value="all">全国</el-radio>
                    <el-radio value="select">选择区域</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col v-show="form.scope === 'select'" :span="24">
                <el-form-item label="选择覆盖范围" prop="serviceArea">
                  <el-input class="w-9/10" v-model="form.serviceArea">
                    <template #append>
                      <el-button @click="areaVisbled = true" type="primary">选择区域</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所属行业" prop="industry">
                  <el-cascader ref="cascaderRef" @change="handleIndustryChange" class="w-9/10" v-model="form.industry"
                    checkOnClickNode :show-all-levels="false" :options="industryOptions"
                    :props="{ multiple: true, checkStrictly: true, emitPath: false }" placeholder="请选择所属行业" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="机构logo" prop="orgLogo">
                  <!-- <el-upload class="avatar-uploader" :show-file-list="false"
                    :action="`${VITE_APP_BASE_URL}/common/upload`"
                    :headers="{ 'Authorization': 'Bearer ' + getToken() }" :limit="1"
                    :on-success="(res) => form.orgLogo = res.url">
                    <img v-if="form.orgLogo" :src="form.orgLogo" class="avatar-uploader-icon" />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload> -->
                  <OneUpload v-model="form.orgLogo"></OneUpload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="预审材料" prop="inquiryMaterials">
                  <el-checkbox-group v-model="form.inquiryMaterials">
                    <el-checkbox value="企业营业执照">企业营业执照</el-checkbox>
                    <el-checkbox value="企业经营情况">企业经营情况</el-checkbox>
                    <el-checkbox value="贷款用途资料">贷款用途资料</el-checkbox>
                    <el-checkbox value="中标通知书">中标通知书</el-checkbox>
                    <el-checkbox value="房产证">房产证</el-checkbox>
                    <el-checkbox value="法人及经办人身份证">法人及经办人身份证</el-checkbox>
                    <el-checkbox value="6个月税务局纳税申报的开票数据">6个月税务局纳税申报的开票数据</el-checkbox>
                    <el-checkbox value="户口本">户口本</el-checkbox>
                    <el-checkbox value="企业人行征信报告">企业人行征信报告</el-checkbox>
                    <el-checkbox value="企业银行账户">企业银行账户</el-checkbox>
                    <el-checkbox value="企业基本信息">企业基本信息</el-checkbox>
                    <el-checkbox value="公司章程">公司章程</el-checkbox>
                    <el-checkbox value="验资报告">验资报告</el-checkbox>
                    <el-checkbox value="主要供销客户的销购合同/协议">主要供销客户的销购合同/协议</el-checkbox>
                    <el-checkbox value="法定代表人(实际控制人)婚姻状况">法定代表人(实际控制人)婚姻状况</el-checkbox>
                    <el-checkbox value="法定代表人(实际控制人)人行征信报告">法定代表人(实际控制人)人行征信报告</el-checkbox>
                    <el-checkbox value="企业纳税信息">企业纳税信息</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="产品补充信息" name="extendInfo">
          <el-form class="pr-7 mt-5" ref="extendInfoRef" :disabled="formDisabled" :model="form.extendInfo"
            :rules="rules" label-width="110px">
            <el-form-item label="产品简介" prop="productDescription">
              <!-- <el-input input-style="height: 100px;" type="textarea"
                                v-model="form.extendInfo.productDescription" :maxlength="1000" show-word-limit
                                placeholder="请输入产品描述" /> -->
              <editor class="!w-full" v-model="form.extendInfo.productDescription" :min-height="192" />
            </el-form-item>
            <el-form-item label="产品特点" prop="productFeature">
              <el-input input-style="height: 100px;" type="textarea" v-model="form.extendInfo.productFeature"
                :maxlength="1000" show-word-limit placeholder="请输入产品特点" />
            </el-form-item>
            <el-form-item label="适用群体" prop="productSuitPopulation">
              <el-input input-style="height: 100px;" type="textarea" v-model="form.extendInfo.productSuitPopulation"
                :maxlength="1000" show-word-limit placeholder="请输入适用群体" />
            </el-form-item>
            <el-form-item label="特此声明" prop="declaration">
              <el-input input-style="height: 100px;" type="textarea" v-model="form.extendInfo.declaration"
                :maxlength="1000" show-word-limit placeholder="请输入特此声明" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="产品补准入要求" name="accessStandard">
          <el-form ref="accessStandardRef" :disabled="formDisabled" :model="form.accessStandard" :rules="rules"
            label-width="140px">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="经营时间大于（月）" prop="operationTimeLimitLower">
                  <el-input v-model="form.accessStandard.operationTimeLimitLower" placeholder="请输入经营时间" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="个体工商户" prop="selfEmployLimit">
                  <el-select clearable v-model="form.accessStandard.selfEmployLimit" placeholder="请选择">
                    <el-option label="禁止申请" :value="0" />
                    <el-option label="允许申请" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="小微企业" prop="microEnterpriseLimit">
                  <el-select clearable v-model="form.accessStandard.microEnterpriseLimit" placeholder="请选择">
                    <el-option label="禁止申请" :value="0" />
                    <el-option label="允许申请" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="注册资本大于（万）" prop="registerFundLimitLower">
                  <el-input v-model="form.accessStandard.registerFundLimitLower" placeholder="请输入注册资本" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="上年度纳税额（万）" prop="preYearPayTaxAmount">
                  <el-input v-model="form.accessStandard.preYearPayTaxAmount" placeholder="请输入上年度纳税额" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="纳税等级要求" prop="payTaxGrade">
                  <el-select v-model="form.accessStandard.payTaxGrade" placeholder="请选择纳税等级" clearable>
                    <el-option v-for="item in ratepayingLevel" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label-width="auto" label="企业持续纳税年限(年)" prop="payTaxDuration">
                  <el-input v-model="form.accessStandard.payTaxDuration" placeholder="请输入持续纳税年限" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="当前贷款余额小于(万)" label-width="auto" prop="loanRemainAmount">
                  <el-input v-model="form.accessStandard.loanRemainAmount" placeholder="请输入当前贷款余额" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label-width="160px" label="企业主年龄要求（岁）" prop="ownerAge">
                  <el-input class="!w-25" v-model="form.accessStandard.ageLimitLower" placeholder="请输入" />
                  <span class="mx-2">~</span>
                  <el-input class="!w-25" v-model="form.accessStandard.ageLimitUpper" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label-width="auto" label="上年度开票营业收入大于(万)" prop="preYearIncome">
                  <el-input v-model="form.accessStandard.preYearIncome" placeholder="请输入上年度开票营业收入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label-width="auto" label="企业当前融资银行数量小于(家)" prop="bankNumber">
                  <el-input v-model="form.accessStandard.bankNumber" placeholder="请输入融资银行数量" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="抵押物要求" prop="guaranteeLimit">
                  <el-select v-model="form.accessStandard.pawnType" placeholder="请选择抵押物类型" clearable>
                    <el-option v-for="dict in pawnType" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label-width="auto" label="抵押物、企业注册地与产品服务范围一致" prop="guaranteeAreaLimit">
                  <el-radio-group v-model="form.accessStandard.guaranteeAreaLimit">
                    <el-radio :value="1">允许申请</el-radio>
                    <el-radio :value="0">禁止申请</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label-width="auto" label="企业注册地与产品服务区域一致" prop="baseAccountNative">

                  <el-radio-group v-model="form.accessStandard.baseAccountNative">
                    <el-radio :value="1">允许申请</el-radio>
                    <el-radio :value="0">禁止申请</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label-width="auto" label="企业基本户在本行限制" prop="baseAccountInBank">

                  <el-radio-group v-model="form.accessStandard.baseAccountInBank">
                    <el-radio :value="1">允许申请</el-radio>
                    <el-radio :value="0">禁止申请</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业欠税限制" prop="owingTax">

                  <el-radio-group v-model="form.accessStandard.owingTax">
                    <el-radio :value="1">允许申请</el-radio>
                    <el-radio :value="0">禁止申请</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label-width="auto" label="企业法人服务区域有房限制" prop="housePropertyArea">

                  <el-radio-group v-model="form.accessStandard.housePropertyArea">
                    <el-radio :value="1">允许申请</el-radio>
                    <el-radio :value="0">禁止申请</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人变更限制" prop="legalPersonChangeLimitMonth">
                  近
                  <el-select class="!w-25 mx-1" v-model="form.accessStandard.legalPersonChangeLimitMonth"
                    placeholder="请选择月数">
                    <el-option label="6" value="6">
                    </el-option>
                    <el-option label="12" value="12">
                    </el-option>
                    <el-option label="24" value="24">
                    </el-option>
                  </el-select>
                  月，变更小于等于
                  <el-input class="!w-25 mx-1" v-model="form.accessStandard.legalPersonChangeLimitNumber"
                    placeholder="请输入"></el-input>
                  次
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div v-if="!formDisabled">
          <div class="dialog-footer" v-if="activeTab == 'basicInfo'">
            <el-button type="primary" @click="basicInfoSubmitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
          <div class="dialog-footer" v-if="activeTab == 'extendInfo'">
            <el-button type="primary" @click="extendInfoSubmitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
          <div class="dialog-footer" v-if="activeTab == 'accessStandard'">
            <el-button type="primary" @click="accessStandardSubmitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showImg" title="预览图片" width="500px">
      <el-image class="w-full" :src="form.onlineAddressUrl" fit="contain"></el-image>
    </el-dialog>
    <area-choose @select="handleSelect" v-model="areaVisbled" />
  </div>
</template>

<script setup lang="ts">
import { getProductByUserOrg, updateProduct, addJrcp, updateBaseInfo, getProducInfo } from '@/api/product'
import OneUpload from '@/components/oneUpload.vue'
import { useDict, transformDict } from '@/hooks/dict'
const { productMainGuaranteeType, productOnlineAddressType, productApplySource, productSecondGuaranteeWay, ratepayingLevel, productType, pawnType, auditStatus, repaymentType, productApproveMode } = useDict('productMainGuaranteeType', 'productSecondGuaranteeWay', 'repaymentType', 'auditStatus', 'productOnlineAddressType', 'productApplySource', 'ratepayingLevel', 'productType', 'pawnType', 'auditStatus', 'repaymentType', 'productApproveMode')

import areaChoose from '@/components/areaChoose.vue'
import { cloneDeep } from 'lodash-es'


// 查询参数
const queryParams = reactive({
  productName: '',
  belongInstitutionName: '',
  page: 1,
  pageSize: 10,
  auditStatus: '',
  mainGuaranteeWay: '',
  applyTimeRange: [],
  auditTimeRange: []
})


import { getIndustryList } from "@/api/common"
import { manageOrganizations } from '@/api/institution'
const industryOptions = ref([])
const { proxy } = getCurrentInstance()
const organizationList = ref([])
onMounted(() => {
  getList()
  getIndustryList().then(res => {
    if (res.code === 200) {
      industryOptions.value = res.data
    }
  })
  manageOrganizations().then(res => {
    if (res.code === 200) {
      organizationList.value = res.rows
    }
  })
})

function handleView(row) {
  formDisabled.value = true
  activeTab.value = 'basicInfo'
  getProducInfo(row.id).then(res => {
    if (res.code === 200) {
      Object.assign(form, res.data)
      form.inquiryMaterials = form.inquiryMaterials.split(',')
      form.industry = form.industries.map(m => m.industryId)
      // form.industry = form.industries.map(m => m.id)
      if (form.serviceAreaCode == '0') {
        form.scope = 'all'
      } else {
        form.scope = 'select'
      }
      open.value = true
    }
  })
}
// 表单查询
function handleEdit(row) {
  formDisabled.value = false
  activeTab.value = 'basicInfo'
  getProducInfo(row.id).then(res => {
    if (res.code === 200) {
      Object.assign(form, res.data)
      form.inquiryMaterials = form.inquiryMaterials.split(',')
      form.industry = form.industries.map(m => m.industryId)
      // form.industry = form.industries.map(m => m.id)
      if (form.serviceAreaCode == '0') {
        form.scope = 'all'
      } else {
        form.scope = 'select'
      }
      open.value = true
    }
  })
}


// 产品表单提交
const handleAdd = () => {
  open.value = true

  formDisabled.value = false
  activeTab.value = 'basicInfo'
}

const form = reactive({
  onlineAddressType: '',
  extendInfo: {},
  accessStandard: {},
  industry: [],
  belongInstitutionName: null,
  belongInstitution: null,
  industries: []
})

const handleScopeChange = (val) => {
  if (form.scope == 'all') {
    form.serviceArea = '全国'
    form.serviceAreaCode = '0'
  }
}

const handleSelectOrg = (orgPath) => {
  const item = organizationList.value.find(f => f.orgPath == orgPath)
  console.log("handles", item);

  if (item) {
    form.belongInstitutionName = item.orgName
    form.belongInstitutionAreaCode = item.district
    form.belongInstitutionType = item.orgType
  }
}

const cascaderRef = ref()
// 选择行业
function handleIndustryChange() {
  const checkedNodes = cascaderRef.value.getCheckedNodes()
  if (checkedNodes.length > 0) {
    form.industries = checkedNodes.map(item => {
      return {
        industryId: item.value,
        industryName: item.label
      }
    })
  }
}

function extendInfoSubmitForm() {
  proxy.$refs["extendInfoRef"].validate(valid2 => {
    activeTab.value = "extendInfo"
    if (!valid2) {
      // 第二个表单验证失败
      return false;
    }

    activeTab.value = "accessStandard"
  })
}

function accessStandardSubmitForm() {
  proxy.$refs["accessStandardRef"].validate(valid3 => {
    if (valid3) {

      const formData = cloneDeep(form)
      formData.inquiryMaterials = formData.inquiryMaterials.join(',')
      formData.publishSource = "1"
      // 所有表单验证通过，可以提交数据
      if (formData.id) {
        updateBaseInfo(formData).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "修改成功",
              type: "success"
            })
            getList()
            cancel()
          }
        })
      } else {
        addJrcp(formData).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "添加成功",
              type: "success"
            })
            getList()
            cancel()
          }
        })
      }

    }
  });
}

function basicInfoSubmitForm() {
  proxy.$refs["basicInfoRef"].validate(valid1 => {
    activeTab.value = "basicInfo"
    if (!valid1) {
      // 第一个表单验证失败
      return false;
    }
    activeTab.value = "extendInfo"
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.id = null
  form.productType = null
  form.productName = null
  form.productShortName = null
  form.belongInstitution = null
  form.mainGuaranteeWay = null
  form.secondGuaranteeWay = null
  form.auditMode = null
  form.onlineAddressType = null
  form.onlineAddressUrl = null
  form.amountLimitLower = null
  form.amountLimitUpper = null
  form.extendInfo = {}
  form.accessStandard = {}
  form.interestRateShow = '0'
  form.loanPeriodLimitLower = null
  form.loanPeriodLimitUpper = null
  form.repaymentWay = null
  form.sort = null
  form.scope = null
}

const rules = reactive({
  productName: [
    { required: true, message: "产品名称不能为空", trigger: "blur" }
  ],
  industry: [
    { required: true, message: "所属行业不能为空", trigger: "change" }
  ],
  inquiryMaterials: [
    { required: true, message: "预审材料不能为空", trigger: "change" }
  ],
  orgLogo: [
    { required: true, message: "机构logo不能为空", trigger: "change" }
  ],
  onlineAddressUrl: [
    { required: true, message: "线上地址不能为空", trigger: "blur" }
  ],
  productDescription: [
    { required: true, message: "产品描述不能为空", trigger: "blur" }
  ],
  productFeature: [
    { required: true, message: "产品特点不能为空", trigger: "blur" }
  ],
  productSuitPopulation: [
    { required: true, message: "适用人群不能为空", trigger: "blur" }
  ],
  declaration: [
    { required: true, message: "特此声明不能为空", trigger: "blur" }
  ],
  productShortName: [
    { required: true, message: "产品简称不能为空", trigger: "blur" }
  ],
  productType: [
    { required: true, message: "产品类型不能为空", trigger: "change" }
  ],
  mainGuaranteeWay: [
    { required: true, message: "担保方式不能为空", trigger: "blur" }
  ],
  secondGuaranteeWay: [
    { required: true, message: "二级担保方式不能为空", trigger: "change" }
  ],
  belongInstitution: [
    { required: true, message: "金融机构不能为空", trigger: "change" }
  ],
  scope: [
    { required: true, message: "适用范围不能为空", trigger: "blur" }
  ],
  auditMode: [
    { required: true, message: "审批模式不能为空", trigger: "blur" }
  ],
  repaymentWay: [
    { required: true, message: "还款方式不能为空", trigger: "blur" }
  ],
  loanPeriodLimitLower: [
    { required: true, message: "贷款期限不能为空", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (form.loanPeriodLimitLower && form.loanPeriodLimitUpper) { // 假设field1和field2是你需要检查的两个字段
          callback(); // 如果两个字段都有值，则通过校验
        } else {
          callback(new Error('请填写开始贷款期限和结束贷款期限'));
        }
      }, trigger: "blur"
    }
  ],
  interestRateLimitLower: [
    { required: true, message: "利率不能为空", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (form.interestRateLimitLower && form.interestRateLimitUpper) { // 假设field1和field2是你需要检查的两个字段
          callback(); // 如果两个字段都有值，则通过校验
        } else {
          callback(new Error('请填写开始利率和结束利率'));
        }
      }, trigger: "blur"
    }
  ],
  amountLimitLower: [
    { required: true, message: "贷款额度不能为空", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (form.amountLimitLower && form.amountLimitUpper) { // 假设field1和field2是你需要检查的两个字段
          callback(); // 如果两个字段都有值，则通过校验
        } else {
          callback(new Error('请填写开始贷款额度和结束贷款额度'));
        }
      }, trigger: "blur"
    }
  ],
})

const activeTab = ref('basicInfo')
const open = ref(false)
const areaVisbled = ref(false)
const formDisabled = ref(false)
const showImg = ref(false)
const title = ref('新增产品')


// 选择适用区域
function handleSelect(nodes) {
  form.serviceArea = nodes.map(m => m.label).join(',')
  form.serviceAreaCode = nodes.map(m => m.regionCode).join(',')

  areaVisbled.value = false
}

const handleSwitchInterestRateShow = (row) => {
  updateProduct({
    id: row.id,
    interestRateShow: row.interestRateShow
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('操作成功')
    }
  })

}
const handleSwitchEnabled = (row) => {
  updateProduct({
    id: row.id,
    enabled: row.enabled
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('操作成功')
    }
  })

}

// 表单引用
const queryFormRef = ref(null)

// 表格数据
const tableData = ref([// 更多数据...
])

// 分页
const total = ref(0)


// 查询
const handleQuery = () => {
  console.log('查询参数:', { ...queryParams })
  getList()
  // 调用 API 获取数据
}

// 重置
const handleReset = () => {
  queryFormRef.value?.resetFields()
  queryParams.applyTimeRange = []
  queryParams.auditTimeRange = []
  handleQuery()
}

const getList = () => {
  getProductByUserOrg(queryParams).then(res => {
    tableData.value = res.rows || []
    total.value = res.total || 0
  })
}


// 多选
const handleSelectionChange = (selection) => {
  console.log('选中项:', selection)
}

</script>

<style scoped lang="scss">
.query-card {
  margin-bottom: 16px;
  border: none;
}

.table-card {
  border: none;
}

.table-header {
  background-color: #f8f8f8 !important;
  height: 60px;
  font-weight: bold;
}
</style>
